package com.nn.indicatorbar;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.example.indicatorbar.R;

public class IndicatorBar extends FrameLayout implements View.OnClickListener{
	private View view;
	private View bar;
	private DisplayMetrics metrics;
	private View layout_1;
	private View layout_2;
	private int barWidth;
	private int duration;
	private int barColor;
	private float barHeight;
	private TextView tvCount;
	public IndicatorBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		TypedArray typesArray=context.obtainStyledAttributes(attrs, R.styleable.animation_attr);
		duration=typesArray.getInt(R.styleable.animation_attr_duration,400);
		barHeight=typesArray.getDimension(R.styleable.animation_attr_bar_height, 3);
		barColor=typesArray.getColor(R.styleable.animation_attr_bar_color, 0xff0000);
		typesArray.recycle();
		view=LayoutInflater.from(context).inflate(R.layout.indicator_view, null);
		metrics=context.getResources().getDisplayMetrics();
		initView();
		this.addView(view);
		setSelectedItem(0);
	}
	private void initView(){
		layout_1=view.findViewById(R.id.layout_1);
		layout_1.setOnClickListener(this);
		layout_2=view.findViewById(R.id.layout_2);
		layout_2.setOnClickListener(this);
		tvCount=(TextView)view.findViewById(R.id.item_count);
		bar=view.findViewById(R.id.bar_view);
		bar.setBackgroundColor(barColor);
		ViewGroup.LayoutParams p=bar.getLayoutParams();
		p.width=(int) (metrics.widthPixels/2.0);
		barWidth=p.width;
		p.height=(int) barHeight;
		bar.setLayoutParams(p);
	}
	private int lastPosition=0;
	Animation anim;
	public void setCountVisiable(boolean bool){
		if(bool){
			tvCount.setVisibility(View.GONE);
		}else{
			tvCount.setVisibility(View.VISIBLE);
		}
	}
	public void setSelectedItem(int index){
		int toPositon=barWidth*(index);
		anim=new TranslateAnimation(Animation.ABSOLUTE, lastPosition, Animation.ABSOLUTE, toPositon, Animation.ABSOLUTE, 0, Animation.ABSOLUTE, 0);
		anim.setFillAfter(true);
		anim.setDuration(duration);
		this.bar.startAnimation(anim);
		lastPosition=toPositon;
	}
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		if(arg0.equals(this.layout_1)){
			setSelectedItem(0);
		}else if(arg0.equals(this.layout_2)){
			setSelectedItem(1);
		}
	}


}
